package th.retrofit.lib;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/multiply-strings/
 * 给定两个以字符串形式表示的非负整数 num1 和 num2，返回 num1 和 num2 的乘积，它们的乘积也表示为字符串形式。
 */
public class Solution43 {

    public String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) return "0";
        final int num1Len = num1.length() - 1;
        final int num2Len = num2.length() - 1;
        StringBuilder target = new StringBuilder();
        for (int i = num1Len; i >= 0; i --) {
            StringBuilder added = new StringBuilder();
            for (int k = 0; k < num1Len - i; k ++) {
                added.insert(0, '0');
            }
            int count = 0;
            for (int j = num2Len; j >= 0 ; j --) {
                int n1 = num1.charAt(i) - '0';
                int n2 = num2.charAt(j) - '0';
                int value = n1 * n2 + count;
                added.insert(0, (char)(value % 10 + '0'));
                count = value / 10;
            }
            if (count != 0) {
                added.insert(0, (char)(count + '0'));
            }
            add(target, added);
        }
        return target.toString();
    }

    private void add(StringBuilder target, StringBuilder added) {
        int count = 0;
        int tLen = target.length();
        int aLen = added.length();
        int len = Math.min(tLen, aLen);
        for (int i = 1; i <= len; i ++) {
            int t = target.charAt(tLen - i) - '0';
            int a = added.charAt(aLen - i) - '0';
            int value = t + a + count;
            target.setCharAt(tLen - i, (char) (value % 10 + '0'));
            count = value / 10;
        }
        if (tLen < aLen) {
            for (int i = aLen - tLen - 1; i >= 0 ; i--) {
                int value = added.charAt(i) - '0' + count;
                target.insert(0, (char) (value % 10 + '0'));
                count = value / 10;
            }
        } else if (tLen > aLen) {
            for (int i = tLen - aLen - 1; i >= 0 ; i--) {
                int value = target.charAt(i) - '0' + count;
                target.setCharAt(i, (char) (value % 10 + '0'));
                count = value / 10;
            }
        }
        if (count != 0) {
            target.insert(0, (char)(count + '0'));
        }
    }

    public static void main(String[] args) {
        StringBuilder target = new StringBuilder();
        target.insert(0, 0);
        target.insert(0, 1);
        target.insert(0, 2);
        target.insert(0, 9);
        target.insert(0, 9);
        StringBuilder added = new StringBuilder();
        added.insert(0, 9);
        added.insert(0, 9);
        added.insert(0, 9);
        added.insert(0, 9);
        new Solution43().add(target, added);
//        System.out.println(target.toString());
        System.out.println(new Solution43().multiply("2", "3"));
    }

}
